package zh;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.Semaphore;

import org.apache.http.Consts;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.message.BasicNameValuePair;

public class FollowUser {
	private static final String MemberFollow = "https://www.zhihu.com/node/MemberFollowBaseV2";
	
	public static void main(String[] args) throws ClientProtocolException, IOException, InterruptedException {
		HttpPost hp = null;
		CloseableHttpClient hc = null;
		
		BufferedReader br = new BufferedReader(new FileReader("d:/x.txt"));
		String uid = null;
		int i = 0;
		while ((uid=br.readLine()) != null) {
//			con = new String(con.getBytes(),"utf-8");
			System.out.printf("%-3s %s\n",i++,uid);
			
			new Thread(new MultiFollow(uid),"t"+i).start();
		}
		
		br.close();
	}
	
	static Semaphore sema = new Semaphore(10);
	
	static class MultiFollow implements Runnable {
		String uid = null;
		
		public MultiFollow(String uid) {
			this.uid = uid;
		}

		@Override
		public void run() {
			int sta = 0;
			int times = 5;
			try {
				sema.acquire();
			} catch (InterruptedException e1) {
				e1.printStackTrace();
			}
			do {
				if (times-- < 0) break;
				
			HttpPost hp = new HttpPost(MemberFollow);
			CloseableHttpClient hc = DefaultConfig.deaultHttpClient(hp);
			addH(hp, "follow_member", uid);
			try {
				CloseableHttpResponse resp = hc.execute(hp);
				sta = resp.getStatusLine().getStatusCode();
				resp.close();
				if (sta != 200) {
					System.out.println(Thread.currentThread().getName()+" LRT:"+times); //LEFT RESEND TIME
				}
//				Thread.sleep((long) (Math.random()*4000)); //Random wait in case of too many requests error at a time...
			} catch (IOException e) {
				e.printStackTrace();
			}
			}while(sta != 200);
			
			sema.release();
		}
	}
	
	public static synchronized void addH(HttpPost httppost, String method, String uid) {
		List<NameValuePair> formparams = new ArrayList<NameValuePair>();
		formparams.add(new BasicNameValuePair("method", method)); //unfollow_member or follow_member
		formparams.add(new BasicNameValuePair("params", "{\"hash_id\":\""+uid+"\"}"));
		
		formparams.add(new BasicNameValuePair("_xsrf",
				"e6ad6299f5d150516ba67cddb5880040"));

		UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams,
				Consts.UTF_8);
		 httppost.setEntity(entity);
	}
}
